<template>
    <div class="product-management">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>产品列表</span>
                    <el-button type="primary" @click="showAddDialog = true">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加产品
                    </el-button>
                </div>
            </template>

            <!-- 搜索区域 -->
            <div class="search-area">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-input v-model="searchForm.search" placeholder="搜索产品名称、档位或合并档" @keyup.enter="handleSearch"
                            clearable>
                            <template #append>
                                <el-button @click="handleSearch">
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </el-button>
                            </template>
                        </el-input>
                    </el-col>
                    <el-col :span="4">
                        <el-select v-model="searchForm.workshop" placeholder="选择车间" clearable @change="handleSearch">
                            <el-option v-for="workshop in workshops" :key="workshop" :label="workshop"
                                :value="workshop" />
                        </el-select>
                    </el-col>
                    <el-col :span="4">
                        <el-button @click="resetSearch">重置</el-button>
                    </el-col>
                </el-row>
            </div>

            <!-- 产品表格 -->
            <el-table v-loading="loading" :data="products" style="width: 100%; font-size: 15px;"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="序号" width="80" />
                <el-table-column prop="workshop" label="车间" min-width="120" />
                <el-table-column prop="product_name" label="产品" min-width="150" show-overflow-tooltip />
                <el-table-column prop="nominal_grade" label="标称档位" min-width="120" />
                <el-table-column prop="merged_grade" label="合并档位" min-width="120" />
                <el-table-column prop="merge_file" label="合并档" min-width="120" show-overflow-tooltip />
                <el-table-column prop="is_active" label="状态" width="80">
                    <template #default="{ row }">
                        <el-tag :type="row.is_active ? 'success' : 'danger'">
                            {{ row.is_active ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="updated_at" label="更新时间" width="150" />
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="editProduct(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteProduct(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 批量操作 -->
            <div v-if="selectedProducts.length > 0" class="batch-actions">
                <el-alert :title="`已选择 ${selectedProducts.length} 项`" type="info" show-icon :closable="false">
                    <template #default>
                        <el-button size="small" type="danger" @click="batchDelete">
                            批量删除
                        </el-button>
                    </template>
                </el-alert>
            </div>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page"
                    :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 添加/编辑产品对话框 -->
        <el-dialog v-model="showAddDialog" :title="editingProduct ? '编辑产品' : '添加产品'" width="600px" @closed="resetForm">
            <el-form ref="productFormRef" :model="productForm" :rules="productRules" label-width="100px">
                <el-form-item label="车间" prop="workshop">
                    <el-input v-model="productForm.workshop" placeholder="请输入车间名称" />
                </el-form-item>

                <el-form-item label="产品名称" prop="product_name">
                    <el-input v-model="productForm.product_name" placeholder="请输入产品名称" />
                </el-form-item>

                <el-form-item label="标称档位" prop="nominal_grade">
                    <el-input v-model="productForm.nominal_grade" placeholder="请输入标称档位" />
                </el-form-item>

                <el-form-item label="合并档位" prop="merged_grade">
                    <el-input v-model="productForm.merged_grade" placeholder="请输入合并档位" />
                </el-form-item>

                <el-form-item label="合并档" prop="merge_file">
                    <el-input v-model="productForm.merge_file" placeholder="请输入合并档文件名" />
                </el-form-item>

                <el-form-item label="启用状态" prop="is_active">
                    <el-switch v-model="productForm.is_active" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddDialog = false">取消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="submitProduct">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 数据定义
const loading = ref(false)
const submitLoading = ref(false)
const showAddDialog = ref(false)
const editingProduct = ref(null)
const products = ref([])
const workshops = ref([])
const selectedProducts = ref([])

// 搜索表单
const searchForm = reactive({
    search: '',
    workshop: ''
})

// 分页信息
const pagination = reactive({
    page: 1,
    per_page: 10,
    total: 0
})

// 产品表单
const productForm = reactive({
    workshop: '',
    product_name: '',
    nominal_grade: '',
    merged_grade: '',
    merge_file: '',
    is_active: true
})

// 表单验证规则
const productRules = {
    workshop: [
        { required: true, message: '请输入车间名称', trigger: 'blur' }
    ],
    product_name: [
        { required: true, message: '请输入产品名称', trigger: 'blur' }
    ],
    nominal_grade: [
        { required: true, message: '请输入标称档位', trigger: 'blur' }
    ],
    merged_grade: [
        { required: true, message: '请输入合并档位', trigger: 'blur' }
    ],
    merge_file: [
        { required: true, message: '请输入合并档文件名', trigger: 'blur' }
    ]
}

// 获取产品列表
const getProducts = async () => {
    loading.value = true
    try {
        const params = {
            page: pagination.page,
            per_page: pagination.per_page,
            search: searchForm.search,
            workshop: searchForm.workshop
        }

        const response = await axios.get('/api/products', { params })

        if (response.data.code === 200) {
            products.value = response.data.data.products
            pagination.total = response.data.data.pagination.total
        }
    } catch (error) {
        console.error('获取产品列表失败:', error)
        ElMessage.error('获取产品列表失败')
    } finally {
        loading.value = false
    }
}

// 获取车间列表
const getWorkshops = async () => {
    try {
        const response = await axios.get('/api/products/workshops')
        if (response.data.code === 200) {
            workshops.value = response.data.data
        }
    } catch (error) {
        console.error('获取车间列表失败:', error)
    }
}

// 搜索处理
const handleSearch = () => {
    pagination.page = 1
    getProducts()
}

// 重置搜索
const resetSearch = () => {
    searchForm.search = ''
    searchForm.workshop = ''
    pagination.page = 1
    getProducts()
}

// 分页处理
const handleSizeChange = (val) => {
    pagination.per_page = val
    pagination.page = 1
    getProducts()
}

const handleCurrentChange = (val) => {
    pagination.page = val
    getProducts()
}

// 选择处理
const handleSelectionChange = (val) => {
    selectedProducts.value = val
}

// 编辑产品
const editProduct = (product) => {
    editingProduct.value = product
    Object.assign(productForm, product)
    showAddDialog.value = true
}

// 删除产品
const deleteProduct = async (product) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除产品 "${product.product_name}" 吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const response = await axios.delete(`/api/products/${product.id}`)

        if (response.data.code === 200) {
            ElMessage.success('删除成功')
            await getProducts()
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除产品失败:', error)
            ElMessage.error('删除产品失败')
        }
    }
}

// 批量删除
const batchDelete = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedProducts.value.length} 个产品吗？`,
            '确认批量删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const ids = selectedProducts.value.map(product => product.id)
        const response = await axios.delete('/api/products/batch', {
            data: { ids }
        })

        if (response.data.code === 200) {
            ElMessage.success(response.data.message)
            selectedProducts.value = []
            await getProducts()
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }
}

// 提交产品
const submitProduct = async () => {
    const productFormRef = ref()
    if (!productFormRef.value) return

    try {
        await productFormRef.value.validate()

        submitLoading.value = true

        let response
        if (editingProduct.value) {
            response = await axios.put(`/api/products/${editingProduct.value.id}`, productForm)
        } else {
            response = await axios.post('/api/products', productForm)
        }

        if (response.data.code === 200) {
            ElMessage.success(editingProduct.value ? '更新成功' : '创建成功')
            showAddDialog.value = false
            await getProducts()
            await getWorkshops()
        }
    } catch (error) {
        console.error('提交产品失败:', error)
        ElMessage.error('提交产品失败')
    } finally {
        submitLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    editingProduct.value = null
    Object.assign(productForm, {
        workshop: '',
        product_name: '',
        nominal_grade: '',
        merged_grade: '',
        merge_file: '',
        is_active: true
    })
}

// 组件挂载
onMounted(() => {
    getProducts()
    getWorkshops()
})
</script>

<style scoped>
.product-management {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    font-size: 18px;
}

.search-area {
    margin-bottom: 20px;
}

.batch-actions {
    margin: 20px 0;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
}

.dialog-footer {
    text-align: right;
}

/* 表格字体大小 */
:deep(.el-table) {
    font-size: 15px;
}

:deep(.el-table th) {
    font-weight: bold;
}
</style>